﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Facebook;
using System.IO.IsolatedStorage;
using Microsoft.Phone.Shell;
using DiscountSharing.FacebookContracts;
using Newtonsoft.Json;
using DiscountSharing.LocalModels;

namespace DiscountSharing
{
    public partial class MainPage : PhoneApplicationPage
    {
        private FacebookClient client;
        private string accessToken;

        // Constructor
        public MainPage()
        {
            InitializeComponent();
            client = new FacebookClient();

            Loaded += (o, e) =>
            {
                AuthBrowser.Navigate(client.GetLoginUrl(new
                {
                    client_id = IsolatedStorageSettings.ApplicationSettings["AppID"],
                    redirect_uri = "https://www.facebook.com/connect/login_success.html",
                    response_type = "token",
                    scope = "friends_status,read_stream,publish_stream,user_photos,photo_upload,friends_photos"
                }));
            };
            AuthBrowser.Navigated += new EventHandler<System.Windows.Navigation.NavigationEventArgs>(AuthBrowser_Navigated);
        }

        void AuthBrowser_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
        {
            FacebookOAuthResult result;
            if (!client.TryParseOAuthCallbackUrl(e.Uri, out result))
            {
                return;
            }

            if (result.IsSuccess)
            {
                accessToken = result.AccessToken;
                PhoneApplicationService.Current.State["accessToken"] = accessToken;
                GetMe();
            }
            else
            {
                MessageBox.Show(result.ErrorDescription);
            }
        }

        private void GetMe()
        {
            client = new FacebookClient(accessToken);

            client.GetCompleted += (o, e) =>
            {
                if (e.Error != null)
                {
                    Dispatcher.BeginInvoke(() => MessageBox.Show(e.Error.Message));
                    return;
                }
                string result = e.GetResultData().ToString();
                FriendPage mePage = JsonConvert.DeserializeObject<FriendPage>(result);
                if (mePage.data.Length != 0)
                {
                    ((App)App.Current).Me = new Friend(mePage.data[0]);
                    Dispatcher.BeginInvoke(() => NavigationService.Navigate(new Uri("/Discounts.xaml?show=all", UriKind.Relative)));
                }
                else
                {
                    Dispatcher.BeginInvoke(() => MessageBox.Show("Cannot find your profile on Facebook!"));
                }
            };

            client.GetAsync("fql",
                new { q = "select uid,name,pic_square,pic from user where uid=me()" });
        }
    }
}